import { PureComponent } from 'react';
import {
  Scene, OrthographicCamera, BoxGeometry, Line, Vector3,
  MeshLambertMaterial, Mesh, WebGLRenderer, DirectionalLight,
  MeshBasicMaterial
} from 'three';
import Stats from 'stats.js';
import { requestAnimationFrame } from '@/utils/requestAnimationFrame';

const drawAxes = scene => {
  const xGeo = new BoxGeometry();
  const xGeoPoints = [
    new Vector3(0, 0, 0),
    new Vector3(3, 0, 0)
  ];
  xGeo.setFromPoints(xGeoPoints);
  const xMat = new MeshBasicMaterial({
    color: 0xff0000
  });
  const xAxis = new Line(xGeo, xMat);
  scene.add(xAxis);

  const yGeo = new BoxGeometry();
  const yGeoPoints = [
    new Vector3(0, 0, 0),
    new Vector3(0, 3, 0)
  ];
  yGeo.setFromPoints(yGeoPoints);
  const yMat = new MeshBasicMaterial({
    color: 0x00ff00
  });
  const yAxis = new Line(yGeo, yMat);
  scene.add(yAxis);

  const zGeo = new BoxGeometry();
  const zGeoPoints = [
    new Vector3(0, 0, 0),
    new Vector3(0, 0, 3)
  ];
  zGeo.setFromPoints(zGeoPoints);
  const zMat = new MeshBasicMaterial({
    color: 0x00ccff
  });
  const zAxis = new Line(zGeo, zMat);
  scene.add(zAxis);
};

const scene = new Scene();

drawAxes(scene);

const camera = new OrthographicCamera(-5, 5, 3.75, -3.75, 0.1, 100);
camera.position.set(5, 5, 20);
camera.lookAt(0, 0, 0);

const light = new DirectionalLight(0xffffff);
light.position.set(20, 10, 5);
scene.add(light);

const geometry = new BoxGeometry(1, 2, 3);

const material = new MeshLambertMaterial({
  color: 0xffff00
});

const mesh = new Mesh(geometry, material);
scene.add(mesh);

let renderer = null;

let animateId = 0;

const stats = new Stats();

const animate = () => {
  stats.begin();
  mesh.rotation.y = (mesh.rotation.y + 0.01) % (Math.PI * 2);
  renderer.render(scene, camera);
  stats.end();
  animateId = requestAnimationFrame(animate);
};

const startAnimate = () => {
  if(animateId) return;
  animateId = requestAnimationFrame(animate);
};

const stopAnimate = () => {
  if(!animateId) return;
  cancelAnimationFrame(animateId);
  animateId = 0;
};

class Index extends PureComponent {

  componentDidMount() {
    renderer = new WebGLRenderer({
      canvas: document.getElementById('mainCanvas')
    });
    renderer.render(scene, camera);
    const fpsContainer = document.getElementById('fps-container');
    //移除fixed定位
    stats.domElement.style.position = '';
    fpsContainer.appendChild(stats.dom);
    startAnimate();
  }

  render() {

    return (
      <div>
        <div>
          <button
            onClick={stopAnimate}
          >暂停</button>
          <button
            onClick={startAnimate}
          >继续</button>
        </div>
        <div
          id="fps-container"
          style={{
            padding: '5px'
          }}
        />
        <canvas
          id="mainCanvas"
          width="400"
          height="300"
        />
      </div>
    );
  }
}

export default Index;